import 'package:flutter/cupertino.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:url_launcher/url_launcher.dart' as url_launcher;
import 'package:website.core/core/application/blocs/url_launcher_bloc/bloc.dart';
import 'package:website.core/injection_container.dart' as core_di;

class RootWidget extends StatefulWidget {
  const RootWidget({
    required this.child,
    Key? key,
  }) : super(key: key);

  final Widget child;

  @override
  State<RootWidget> createState() => _RootWidgetState();
}

class _RootWidgetState extends State<RootWidget> {
  UrlLauncherBloc get _urlLauncherBloc {
    return core_di.sl<UrlLauncherBloc>();
  }

  void _onUrlLauncherBlocStateChanged({
    required UrlLauncherBlocState state,
  }) {
    if (state.url != null) {
      final url = Uri.parse(state.url!);

      url_launcher.launchUrl(
        url,
        webOnlyWindowName: '_self',
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    return BlocListener<UrlLauncherBloc, UrlLauncherBlocState>(
      bloc: _urlLauncherBloc,
      listener: (context, state) {
        _onUrlLauncherBlocStateChanged(
          state: state,
        );
      },
      child: widget.child,
    );
  }
}
